package hu.rsc.forbiddenwords.client.gui.language;

import hu.rsc.forbiddenwords.client.util.Logger;
import hu.rsc.forbiddenwords.shared.LanguageDTO;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

public class LanguageForm extends Composite {
    private LanguagePanel parent;

    private FlexTable form = new FlexTable();

    private TextBox nameTb;
    private TextBox codeTb;

    private LanguageDTO entry = new LanguageDTO(0l);

    public LanguageForm(LanguagePanel parent) {
	this.parent = parent;
	buildContent();
	initWidget(this.form);
    }

    public LanguageDTO getEntry() {
	return this.entry;
    }

    public void refresh(LanguageDTO entry) {
	this.entry = entry;
	buildContent();
    }

    private void buildContent() {
	this.form.clear();
	this.form.addStyleName("form");
	this.form.addStyleName("border");
	int row = 0;

	Label lb = new Label();
	lb.addStyleName("formlabel");
	lb.setText("name");
	this.form.setWidget(row, 0, lb);
	this.nameTb = new TextBox();
	this.nameTb.addStyleName("forminput");
	this.form.setWidget(row, 1, this.nameTb);
	this.nameTb.setValue(this.entry.getName());
	row++;

	lb = new Label();
	lb.addStyleName("formlabel");
	lb.setText("code");
	this.form.setWidget(row, 0, lb);
	this.codeTb = new TextBox();
	this.codeTb.addStyleName("forminput");
	this.form.setWidget(row, 1, this.codeTb);
	this.codeTb.setValue(this.entry.getCode());
	row++;

	HorizontalPanel buttonPanel = new HorizontalPanel();
	buttonPanel.addStyleName("buttonpanel");
	this.form.setWidget(row, 0, buttonPanel);
	this.form.getFlexCellFormatter().setColSpan(row, 0, 2);

	Button save = new Button();
	save.setText("Save");
	buttonPanel.add(save);

	save.addClickHandler(new ClickHandler() {

	    @Override
	    public void onClick(ClickEvent event) {
		if (validate()) {
		    LanguageForm.this.parent.save(LanguageForm.this.entry);
		}
	    }
	});

	Button newBt = new Button();
	newBt.setText("New");
	buttonPanel.add(newBt);
	newBt.addClickHandler(new ClickHandler() {

	    @Override
	    public void onClick(ClickEvent event) {
		refresh(new LanguageDTO(0l));
	    }
	});

    }

    private boolean validate() {
	this.entry.setName(this.nameTb.getValue());
	this.entry.setCode(this.codeTb.getValue());

	StringBuilder error = new StringBuilder();
	if (this.entry.getName() == null || this.entry.getName().length() == 0) {
	    error.append("The name is empty.");
	}

	if (this.entry.getCode() == null || this.entry.getCode().length() == 0) {
	    error.append("The code is empty.");
	}

	if (error.length() > 0) {
	    Logger.logError(error.toString());
	    return false;
	}
	return true;
    }
}
